package my.processmanager;


import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author shaw
 */
public class ProcessManagerUI extends javax.swing.JFrame {
    
    //final int MAX_PROCESS = 30;     //最大进程数
    List<MyProcess> lists = new ArrayList<>();
    
    /**
     * 新建JDialog类
     */
    class MyJDialog extends JDialog {
        public MyJDialog(ProcessManagerUI frame, String name){      
		super(frame,"进程信息",true);
                
                MyProcess myp = new MyProcess();
                for(MyProcess a:lists){
                    if(a.getName().equals(name)){
                        myp = a;
                        break;
                    }
                }
                if(myp.getPath() == null) {
                    //空值处理
                }
                SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
                String time = aDate.format(myp.getStartTime());
                //判断进程状态
                boolean bool = myp.isRun();
                
                
		Container container=this.getContentPane();          //创建一个容器
                JPanel jPanel = new JPanel();
                //jPanel.setLayout(new BoxLayout(jPanel,BoxLayout.Y_AXIS));
                jPanel.setLayout(new GridLayout(7,1,50,20));
                
                Font f = new Font("宋体", Font.PLAIN, 16);
                JLabel nameJLabel = new JLabel("名称："+ myp.getName());
                nameJLabel.setFont(f);
                JLabel stateJLabel = new JLabel("状态：" + myp.getProcessState());
                stateJLabel.setFont(f);
                JLabel timeJLabel = new JLabel("开始运行时间：" + time);
                timeJLabel.setFont(f);
                JLabel parmJLabel = new JLabel("执行时所用参数：" + myp.getParm());
                parmJLabel.setFont(f);
                JLabel PIDJLabel = new JLabel("PID：" + myp.getPID());
                PIDJLabel.setFont(f);
                JLabel pathJLabel = new JLabel("文件所在位置：" + myp.getPath());
                pathJLabel.setFont(f);
                
		jPanel.add(nameJLabel);         //在容器中添加进程名称
                jPanel.add(stateJLabel);        //运行状态
                jPanel.add(timeJLabel);        //添加进程开始时间
                jPanel.add(parmJLabel);         //参数
                jPanel.add(PIDJLabel);          //添加进程PID
                jPanel.add(pathJLabel);        //添加文件所在位置
                if(myp.getProcessState().equals("Running")){
                    JButton shutButton = new JButton("关闭进程");
                    shutButton.addActionListener(new shut(myp, this));
                    jPanel.add(shutButton);
                }
                container.add(jPanel);
		setBounds(220,220,500,400);                       //设置对话框窗体大小
	}
    }
    
    /**
     * 自定义Item监听事件
     */
    public ItemListener itemListener = new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                int stateChange = e.getStateChange();
                JCheckBox j1 = (JCheckBox)e.getSource();
                if(stateChange == ItemEvent.SELECTED) {
                    String s1 = jTextField2.getText();
                    jTextField2.setText(s1+" "+j1.getText());
                }
            }
        };
    /**
     * 自定义进程“Detail”按钮点击事件,无法传入参数
     */
    /*public ActionListener detailBtnListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new MyJDialog(ProcessManagerUI.this).setVisible(true);
        }
    };*/
    
    
    
    /**
     * detail按钮监听
     * 利用接口构造函数向监听事件传入参数
     */
    public class detail implements ActionListener{
        String name;
        //构造函数传参
        public detail(String name) {
            this.name = name;
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            new MyJDialog(ProcessManagerUI.this, name).setVisible(true);
        }
    }
    
    /**
     * 在打开的dialog中点击关闭进程
     */
    public class shut implements ActionListener{
        MyProcess p;
        JDialog jDialog;
        public shut(MyProcess p, JDialog jDialog) {
            this.p = p;
            this.jDialog = jDialog;
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            p.shutdown();
            jDialog.dispose();
            new MyJDialog(ProcessManagerUI.this, p.getName()).setVisible(true);
        }
    }
    
    /**
     * 自定义添加进程状态布局
     * @param processName
     * @param processState
     */
    public void processManagerLayout(String processName, String processState){
        this.jPanel8.setLayout(new BoxLayout(jPanel8,BoxLayout.Y_AXIS));
        Font font = new Font("宋体", Font.PLAIN, 16);
        JPanel pManager = new JPanel();
        //pManager.setPreferredSize(new Dimension(200,40));
        JLabel processNameJLabel = new JLabel(processName);
        processNameJLabel.setFont(font);
        processNameJLabel.setSize(40, 30);
        JLabel processStateJLabel = new JLabel(processState, JLabel.CENTER);
        processStateJLabel.setFont(font);
        processStateJLabel.setSize(40, 30);
        JButton processDetailButton = new JButton("Detail");
        processDetailButton.addActionListener(new detail(processName));
        
        pManager.setLayout(new BorderLayout());
        pManager.add("West", processNameJLabel);
        pManager.add("Center", processStateJLabel);
        pManager.add("East", processDetailButton);
        jPanel8.add(pManager);
        //pManager.setVisible(true);
        //pManager.setSize(200, 30);
        jPanel8.revalidate();
        
        
    }

    /**
     * Creates new form ProcessManagerUI
     */
    public ProcessManagerUI() {  
        initComponents();
        
        this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e)
          {
             for(MyProcess aMyProcess:lists){
                 if (!aMyProcess.getProcessState().equals("Down")) {
                     //JDialog jDialog = new JDialog();
                     int i = JOptionPane.showConfirmDialog(null, "还有进程在运行，确定退出吗？", "退出",JOptionPane.YES_NO_OPTION);
                     if(i==JOptionPane.YES_OPTION){
                        System.exit(0);
                    }else{
                         return;
                     }
                 }
             }
             System.exit(0);
          }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        errorLabel = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel7 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JARManager");
        setLocationByPlatform(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setToolTipText("11");

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Optional Parm:"));
        jPanel3.setToolTipText("");
        jPanel3.setPreferredSize(new java.awt.Dimension(410, 315));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 398, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        errorLabel.setForeground(new java.awt.Color(255, 0, 0));

        jButton2.setText("Run");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("File:");

        jTextField1.setFont(new java.awt.Font("宋体", 0, 16)); // NOI18N
        jTextField1.setText("选择文件/输入文件路径");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setText("View");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(27, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        jLabel2.setText("Parm:");

        jTextField2.setFont(new java.awt.Font("宋体", 0, 16)); // NOI18N
        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(errorLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton2))
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addGap(10, 10, 10))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 318, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(errorLabel)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setToolTipText("22");

        jLabel7.setText("Management：");

        jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel3.setFont(new java.awt.Font("宋体", 0, 16)); // NOI18N
        jLabel3.setText("Process");

        jLabel4.setFont(new java.awt.Font("宋体", 0, 16)); // NOI18N
        jLabel4.setText("State");

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addGap(122, 122, 122)
                .addComponent(jLabel4)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addGap(0, 4, Short.MAX_VALUE))
        );

        jPanel8.setAutoscrolls(true);

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 379, Short.MAX_VALUE)
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 351, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jScrollPane1.setViewportView(jPanel7);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1)
                .addContainerGap())
        );

        jButton4.setText("Refresh");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton4)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton4)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    //浏览文件按钮处理事件
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle("Choose File");
        chooser.setMultiSelectionEnabled(true);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("jar", "jar");
        chooser.setFileFilter(filter);
        chooser.showOpenDialog(null);
        if(chooser.getSelectedFile() == null) {
            return ;
        }
        File file = chooser.getSelectedFile();
        //读取成功
        jTextField1.setText(file.getPath());
        
        /**
         * 读取指定jar文件，显示可选参数列表
         **/
        String string = new String();   //jar文件的URL路径
        String str = new String();  //readme文件中的内容
        string = "jar:file:/"+file.getPath()+"!/readme";
        try {
            URL url = new URL(string);
            //System.out.println(url);
            InputStream inputStream = url.openStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            //byte b[] = new byte[10000];
            char[] b = new char[10000];
            int len = 0;
            len = inputStreamReader.read(b);
            //inputStreamReader.read(b);
            //str = new String(b,"utf-8").trim();
            str = new String(b,0,len).trim();
            //System.out.println(str);
            
        } catch (IOException e) {
            System.out.println("Exception thrown  :" + e);
            errorLabel.setText("Exception:" + e);
        }
        //过滤str中无关内容，将参数列表格式输出
        String []a = str.split("\\r\\n"); //分割字符串第一步
        String [][]b = new String[a.length][2]; //详细分割，b存储的是参数
        int countParm = 0;  //记录参数个数
        int temp = a.length;
        int k=0;
        //填充b
        for(int i=0; i<temp; i++){
            String c[]=a[k++].split("##");
            if(c.length>1){
                countParm++;
             for(int j=0; j<c.length; j++){
                b[i][j] = c[j];
                //System.out.println("["+i+"]"+"["+j+"]:");
                //System.out.println(b[i][j]);
            }
            }else {
                temp--;
                i--;
            }
        }
        // 重绘界面
        this.jPanel3.removeAll();
        this.jPanel3.setVisible(false);
        this.jPanel3.repaint();
        this.jPanel3.setVisible(true);
        this.errorLabel.setText("");
        //将b中的数据读取并动态显示到参数框中
        jPanel3.setLayout(new BorderLayout());
        JPanel jPanel= new JPanel(new GridLayout(countParm,1,10,10));
        JPanel[] parmJPanel = new JPanel[countParm];
        JCheckBox[] parmjCheckBox = new JCheckBox[countParm];
        JLabel[] parmJLabel = new JLabel[countParm];
        Font fnt=new Font("宋体",Font.ITALIC,15);
        ////设置布局样式
        //jPanel.setLayout(new GridLayout(countParm,1,10,10));
        //jPanel.setLayout(null);
        for(int i=0; i<countParm; i++) {
            parmJPanel[i] = new JPanel();
            jPanel.add(parmJPanel[i]);
            //parmJPanel[i].setLayout(new BoxLayout(parmJPanel[i], BoxLayout.X_AXIS));
            parmjCheckBox[i] = new JCheckBox();
            parmJLabel[i] = new JLabel();
            parmjCheckBox[i].setText(b[i][0]);
            parmjCheckBox[i].setFont(new Font("宋体", Font.CENTER_BASELINE, 15));
            parmJLabel[i].setText(b[i][1]);
            parmJLabel[i].setFont(fnt);
            //parmJPanel[i].setLayout(new GridLayout(1,2));
            FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT,10,10);
            parmJPanel[i].setLayout(flowLayout);
            parmJPanel[i].add(parmjCheckBox[i]);
            parmJPanel[i].add(parmJLabel[i]);
            parmjCheckBox[i].addItemListener(itemListener);
            
        }
        //jScrollPane.setViewportView(jPanel);
        //jPanel.setSize(400,300);
        JScrollPane jScrollPane = new JScrollPane(jPanel);
        //jScrollPane.setLayout(null);
        //jScrollPane.setLocation(7, 7);
        //jPanel.setBounds(5, 5, 400, 300);
        jPanel3.add(jScrollPane, BorderLayout.CENTER);
        
        
        //重绘面板
        jPanel3.revalidate();
        jPanel3.repaint();
        
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField2ActionPerformed

    /**
     * Run按钮的监听事件
     * @param evt 
     */
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        
        /*String processName = new String();
        String temp1 = jTextField1.getText();
        System.out.println(temp1);
        String[] temp2 = temp1.split("\\\\");
        processName = temp2[temp2.length-1];*/
        
        //判断是否重复运行
        String[] temp1 = jTextField1.getText().trim().split("\\\\");
        String[] temp2 = temp1[temp1.length-1].split(".jar");
        //boolean renewBool = false;  //判断是否之前已运行，true代表已运行，但是Down了，false代表未运行
        for(MyProcess a:lists){
                if (temp2[0].equals(a.getName()) && a.getProcessState().equals("Down")){
                    //renewBool = true;
                    lists.remove(a);
                }else if(temp2[0].equals(a.getName())){
                    errorLabel.setText("请勿重复运行！");
                    return;
                }
            }
        
        try {
            Process p = null;
            //String toRun = "java -jar " +  jTextField1.getText().trim() + " " + jTextField2.getText().trim();
            //p = Runtime.getRuntime().exec(toRun);
            //p.waitFor(); //进程执行完才能往下。//这句话得放在子线程中执行？
            
            //执行java -jar命令，并获取进程对应PID
            MyProcess myProcess = new MyProcess(jTextField1.getText().trim(), jTextField2.getText().trim());
            String result = myProcess.getResult();
            lists.add(myProcess);
            //Long pid = myProcess.getPID();
            //System.out.println("PID:"+pid);
            
            String[] form = result.split("##"); //分割返回的结果，第一个为消息类型
            System.out.println(result);
            if (form[0].equals("Input")) {
                System.out.println("程序"+ myProcess.getName() +"正常运行");
                if (form.length > 1) {
                 System.out.println(form[1]);   
                }
                processManagerLayout(myProcess.getName(), "Running");
            }
            else if(form[0].equals("0")) {
                System.err.println("创建命令行程序失败！");
                errorLabel.setText("无法创建命令运行"+ form[1]);
                return ;
            }else if(form[0].equals("Error")){
                System.err.println("Error：程序执行过程中发生错误！");
                errorLabel.setText("程序执行过程中发生错误！"+ form[1]);
                return;
            }
            this.jPanel3.removeAll();
            this.jPanel3.setVisible(false);
            this.jPanel3.repaint();
            this.jPanel3.setVisible(true);
            
            jTextField1.setText("选择文件/输入文件路径");
            jTextField2.setText("");
            
        } catch (Exception e) {
            System.out.println("Exception:"+e);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * 刷新按钮事件处理
     * @param evt 
     */
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        //重绘进程管理界面
        this.jPanel8.removeAll();
        this.jPanel8.setVisible(false);
        this.jPanel8.repaint();
        this.jPanel8.setVisible(true);
        //存活进程
        for(MyProcess a:lists){
            a.isRun();  //判断进程是否还活着
            if(a.getProcessState().equals("Running")){
                processManagerLayout(a.getName(), a.getProcessState());
            }
        }
        //等待进程
        for(MyProcess b:lists){
            if(b.getProcessState().equals("Waiting")){
                processManagerLayout(b.getName(), b.getProcessState());
            }
        }
        //已Down进程
        for(MyProcess c:lists){
            if(c.getProcessState().equals("Down")){
                processManagerLayout(c.getName(), c.getProcessState());
            }
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ProcessManagerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ProcessManagerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ProcessManagerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ProcessManagerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new ProcessManagerUI().setVisible(true);
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel errorLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
